<template>
  <div v-if="isLoading" class="loading-container">
    <div class="spinner" />
    <p>数据处理中，请稍候...</p>
  </div>
  <div v-else ref="chartRef" class="chart" />
</template>

<script setup>
import { ref, onMounted, defineExpose } from "vue";
import { useECharts } from "@pureadmin/utils";
import { codeClean } from "@/api/dataProcessing";
import * as echarts from "echarts/core";
import { ScatterChart } from "echarts/charts"; // 导入散点图模块

echarts.use([ScatterChart]); // 注册散点图模块
import { LineChart } from "echarts/charts"; // 导入折线图模块
echarts.use([LineChart]); // 注册折线图模块

// const fileName = ref("fakeData.json"); // 假文件名
const c_way = ref(1);
const chartYName = ref("齿轮振动传感器加速度数据");
const childStatusObj = ref({
  title: "未清洗",
  status: 500
});

// 创建一个假的文件对象
// const fileDataObj = ref(
//   new File([JSON.stringify({ data: "这是假的数据" })], "fakeData.json", {
//     type: "application/json"
//   })
// );

const emit = defineEmits(["childTitleStatusClick"]);
emit("childTitleStatusClick", childStatusObj.value);

const props = defineProps({
  selectValue: {
    type: Object,
    default() {
      return {};
    }
  },
  switchValue: {
    type: Array,
    default() {
      return [];
    }
  },
  fileData: {
    type: Object,
    default: null
  },
  fileName: {
    type: String,
    default: ""
  },
  currentDevice: {
    type: String,
    default: ""
  }
});

onMounted(() => {
  render();
});

const chartRef = ref();
const chartData = ref([
  { data: [], name: "原始数据" },
  { data: [], name: "修复数据" }
]);
const { setOptions } = useECharts(chartRef, {});
const render = () => {
  const legendData = props.currentDevice
    ? [`${props.currentDevice} 原始数据`, `${props.currentDevice} 修复数据`]
    : ["原始数据", "修复数据"];

  // 根据当前设备修改 yAxis 的 name
  const yAxisName = props.currentDevice === "整经机" ? "经长/m" : "转速/min";

  setOptions({
    title: {
      top: "5%",
      textStyle: { fontSize: 16 },
      text: props.currentDevice ? `${props.currentDevice} ` : ""
    },
    tooltip: { trigger: "axis" },
    legend: {
      right: "15%",
      data: legendData,
      icon: "roundRect",
      top: "5%",
      textStyle: { fontSize: 14 }
    },
    grid: {
      top: "20%",
      left: "0%",
      right: "10%",
      bottom: "10%",
      containLabel: true
    },
    xAxis: {
      axisTick: { show: false },
      axisLabel: { margin: 15 },
      name: "样本点/个",
      type: "category",
      boundaryGap: true
    },
    yAxis: { name: yAxisName, type: "value" }, // 根据设备类型动态设置 Y 轴名称
    series: [
      {
        name: legendData[0],
        type: "scatter",
        data: chartData.value[0].data
      },
      {
        name: legendData[1],
        type: "scatter",
        data: chartData.value[1].data
      }
    ]
  });
};

const childMethod1 = () => {
  chartData.value[0] = {};
  chartData.value[1] = {};
  isLoading.value = true; // 开始加载
  childStatusObj.value.title = "清洗中....";
  emit("childTitleStatusClick", childStatusObj.value);

  let formData = new FormData();
  formData.append("type", props.selectValue.selectA);
  formData.append("file", fileDataObj.value);

  console.log("上传的文件:", fileDataObj.value);
  // 添加一个加载状态变量
  const isLoading = ref(false); // 是否正在加载
  codeClean(formData)
    .then(res => {
      if (res.status === 200) {
        chartData.value[0].data = res.data.oridata;
        chartData.value[1].data = res.data.prodata;

        render();
        if (res.data.oridata.length > 0) {
          childStatusObj.value.title = "清洗完成";
          childStatusObj.value.status = res.status;
        }
      } else {
        childStatusObj.value.title = "清洗失败";
        childStatusObj.value.status = res.status;
      }
    })
    .catch(error => {
      childStatusObj.value.title = "清洗失败";
      childStatusObj.value.status = error.status;
      console.log(error);
    })
    .finally(() => {
      // 数据返回后停止加载
      isLoading.value = false;
      emit("childTitleStatusClick", childStatusObj.value);
    });
};
// const childMethod = () => {
//   // 检查是否接收到文件
//   if (!props.fileData) {
//     childStatusObj.value.title = "未收到文件";
//     childStatusObj.value.status = 400;
//     emit("childTitleStatusClick", childStatusObj.value);
//     return;
//   }

//   chartData.value[0] = {};
//   chartData.value[1] = {};

//   childStatusObj.value.title = "清洗中....";
//   emit("childTitleStatusClick", childStatusObj.value);

//   let formData = new FormData();
//   formData.append("type", props.selectValue.selectA);
//   formData.append("file", props.fileData);

//   console.log("上传的文件:", props.fileData);

//   codeClean(formData)
//     .then(res => {
//       if (res.status === 200) {
//         chartData.value[0].data = res.data.oridata;
//         chartData.value[1].data = res.data.prodata;
//         render();
//         if (res.data.oridata.length > 0) {
//           childStatusObj.value.title = "清洗完成";
//           childStatusObj.value.status = res.status;
//         }
//       } else {
//         childStatusObj.value.title = "清洗失败";
//         childStatusObj.value.status = res.status;
//       }
//     })
//     .catch(error => {
//       childStatusObj.value.title = "清洗失败";
//       childStatusObj.value.status = error.status || 500;
//       console.log(error);
//     })
//     .finally(() => {
//       emit("childTitleStatusClick", childStatusObj.value);
//     });
// };
let currentRequestId = null; // 定义当前请求的唯一标识
const isLoading = ref(false); // 是否正在加载
const childMethod = () => {
  if (!props.fileData) {
    childStatusObj.value.title = "未收到文件";
    childStatusObj.value.status = 400;
    emit("childTitleStatusClick", childStatusObj.value);
    return;
  }

  // 清空 chartData
  chartData.value[0] = {};
  chartData.value[1] = {};
  isLoading.value = true; // 开始加载
  // 设置清洗中的状态
  childStatusObj.value.title = "清洗中....";
  emit("childTitleStatusClick", childStatusObj.value);

  // 创建唯一的请求标识
  const requestId = Date.now();
  currentRequestId = requestId;

  // 创建新的 FormData 实例
  const formData = new FormData();
  formData.append("type", props.selectValue.selectA);
  formData.append("file", props.fileData);

  console.log("上传的文件:", props.fileData);

  codeClean(formData)
    .then(res => {
      // 检查是否是最新的请求
      if (currentRequestId !== requestId) return;

      if (res.status === 200) {
        chartData.value[0].data = res.data.oridata;
        chartData.value[1].data = res.data.prodata;
        render();
        if (res.data.oridata.length > 0) {
          childStatusObj.value.title = "清洗完成";
          childStatusObj.value.status = res.status;
        }
      } else {
        childStatusObj.value.title = "清洗失败";
        childStatusObj.value.status = res.status;
      }
    })
    .catch(error => {
      // 检查是否是最新的请求
      if (currentRequestId !== requestId) return;

      childStatusObj.value.title = "清洗失败";
      childStatusObj.value.status = error.status || 500;
      console.error(error);
    })
    .finally(() => {
      // 数据返回后停止加载
      isLoading.value = false;
      emit("childTitleStatusClick", childStatusObj.value);
    });
};

defineExpose({
  childMethod
});
</script>

<style lang="scss" scoped>
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(0, 0, 0, 0.1);
  border-top-color: #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.chart {
  height: 300px;
  width: 100%;
}
</style>
